import 'package:flutter/material.dart';
import 'package:flutter_default_project/models.dart';
import 'package:flutter_default_project/state_container.dart';

class AddEditScreen extends StatefulWidget {
  final Todo? todo;
  const AddEditScreen({super.key, this.todo});
  @override
  State<AddEditScreen> createState() => _AddEditScreenState();
}

class _AddEditScreenState extends State<AddEditScreen> {
  final _formKey = GlobalKey<FormState>();
  String? task;
  String note = "";
  get isEditing => widget.todo != null;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: isEditing ? Text('Edit Todo') : Text('Add Todo')),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Form(
          key: _formKey,
          child: Column(
            children: [
              TextFormField(
                initialValue: widget.todo?.task,
                decoration: const InputDecoration(
                  labelText: 'Task',
                  hintText: 'Enter task description',
                  border: OutlineInputBorder(),
                ),
                validator: (value) {
                  if (value == null || value.trim().isEmpty) {
                    return 'Task cannot be empty';
                  }
                  if (value.trim().length < 3) {
                    return 'Task must be at least 3 characters long';
                  }
                  return null;
                },
                onSaved: (value) => task = value?.trim(),
              ),
              const SizedBox(height: 16),
              TextFormField(
                initialValue: widget.todo?.note,
                decoration: const InputDecoration(
                  labelText: 'Note',
                  hintText: 'Enter additional notes (optional)',
                  border: OutlineInputBorder(),
                ),
                maxLines: 3,
                validator: (value) {
                  // Note is optional, but if provided, should have minimum length
                  if (value != null &&
                      value.trim().isNotEmpty &&
                      value.trim().length < 2) {
                    return 'Note must be at least 2 characters long';
                  }
                  return null;
                },
                onSaved: (newValue) => note = newValue ?? "",
              ),
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          if (_formKey.currentState!.validate()) {
            _formKey.currentState!.save();
            if (widget.todo != null) {
              Navigator.pop(context, widget.todo);
            } else {
              // Create new todo
              StateContainer.of(context).addTodo(Todo(task!, note: note));
              Navigator.pop(context);
            }
          }
        },
        child: Icon(Icons.check),
      ),
    );
  }
}
